package com.lkcg.demo.utils.api;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.function.Function;
import java.util.function.Supplier;

public class ResultObject<T> {

    private static final Logger LOG = LoggerFactory.getLogger(ResultObject.class);

    private Long status = ResultStatus.OK;

    private Long code;

    private String message;

    private T data;

    public static <T> ResultObject<T> getResultObject(Supplier<T> s) {
        ResultObject<T> result = new ResultObject<T>();
        try {
            T t = s.get();
            result.setData(t);
            result.setResultCode(ResultCode.SUCCESS);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            result.setResultCode(ResultCode.FAILURE);
        }

        return result;
    }

    public static <T> ResultObject<T> getResultObject(Function<ResultObject<T>, T> s) {
        ResultObject<T> result = new ResultObject<T>();
        try {
            T r = s.apply(result);

            if (result.getMessage() == null) {
                result.setData(r);
                result.setResultCode(ResultCode.SUCCESS);
            }

        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            result.setResultCode(ResultCode.FAILURE);
        }

        return result;
    }

    public void setResultCode(ResultCode resultCode) {
        this.setMessage(resultCode.getValue());
        this.setCode(resultCode.getKey());
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public Long getStatus() {
        return status;
    }

    public void setStatus(Long status) {
        this.status = status;
    }

    public Long getCode() {
        return code;
    }

    public void setCode(Long code) {
        this.code = code;
    }
}
